package com.jiuan.transfer.redis;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.jiuan.transfer.mqtt.domain.Config;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @Title: RedisUtil.java
 * @Package com.jiuan.transfer.redis
 * @Description: TODO
 * @author Lee
 * @date 2016年8月16日 上午11:37:49
 * @version V1.0
 */

public class SingleRedisUtil {

    private static GenericObjectPoolConfig config;
    private static JedisPool pool;

    static{
        initJedisPool();
    }


    private static synchronized void resetJedisPool(){
        if(!pool.isClosed())return;
        pool.destroy();
        initJedisPool();
    }
    private static void initJedisPool(){
        config=new GenericObjectPoolConfig();
        config.setBlockWhenExhausted(true);//没有空闲连接时阻塞，默认false，直接异常
        config.setMaxWaitMillis(3000);//阻塞等待时间
        config.setMaxIdle(50);
        config.setTestWhileIdle(true);
        config.setMaxTotal(100);
        config.setTestOnBorrow(false);//获取连接时不ping测试
        config.setTestOnReturn(false);//归还连接时不ping测试
        pool= new JedisPool(config,Config.getRedis_ip(), Config.getRedis_port(),Config.getRedis_timeout());
    }

    public static Set<String> queryIps(String topic) {
        try {
            if(StringUtils.isEmpty(topic))return null;
            Set<String> ips = new HashSet<String>();
            Jedis jc = pool.getResource();
            Set<String> s = jc.smembers(topic);
            for (String id : s) {
                ips.add(jc.get(id));
            }
            pool.returnResource(jc);
            return ips;
        } catch (Exception e) {
            if(e instanceof java.net.ConnectException){
                System.out.println("Jedis pool: "+e.getMessage());
                resetJedisPool();
            }else{
                throw e;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        Set<String> ips = queryIps("TOPIC_T1");
        System.out.println("ips:" + ArrayUtils.toString(ips.toArray()));

    }
}
